import { View, Text } from '@tarojs/components';
import { Button } from '@nutui/nutui-react-taro';
import Taro, { useRouter } from '@tarojs/taro';
import { useMemo, useEffect } from 'react';
import { usePreselectStore } from '@/models';
import { FourGreatEnum } from '@/interfaces/fourGreat';
import { Empty } from '@/components';
import { Toast } from '@/utils/toast';
import { postApiChoiceCreate } from '@/api';
import { useRequest } from '@/hooks';
import { StorageKey } from '@/constants/storage';
import { RouterUtil, TabbarUtil } from '@/utils';
import './index.scss';
import { useDidShow } from '@tarojs/taro';
import { BasicLayout } from '@/layouts';
import DressItem from './DressItem';
import qs from 'qs';

// 四大金刚类型映射
const fourGreatTypeMap = new Map([
  [FourGreatEnum['化妆师'], '化妆师'],
  [FourGreatEnum['司仪'], '司仪'],
  [FourGreatEnum['摄影'], '摄影师'],
  [FourGreatEnum['婚庆'], '婚庆'],
]);

const Preselect = () => {
  const router = useRouter();
  const { dresses, persons, removeDress, removePerson, clearAll } = usePreselectStore();

  // 提交预选
  const { loading: submitting, run: submitPreselect } = useRequest(postApiChoiceCreate, {
    manual: true,
    onSuccess: () => {
      Toast.success('提交成功');
      clearAll();
    },
    onError: (error) => {
      Toast.info(error?.message || '提交失败，请重试');
    },
  });

  // 计算总数
  const totalCount = useMemo(() => {
    return dresses.length + persons.length;
  }, [dresses.length, persons.length]);

  // 页面显示时更新 tabbar badge
  useDidShow(() => {
    TabbarUtil.setPreselectBadge(totalCount);
  });

  // 监听预选数量变化，实时更新 tabbar badge
  useEffect(() => {
    TabbarUtil.setPreselectBadge(totalCount);
  }, [totalCount]);

  // 获取人员类型名称
  const getPersonTypeName = (bigType?: number) => {
    if (!bigType) return '未知';
    return fourGreatTypeMap.get(bigType) || '未知';
  };

  // 处理提交预选
  const handleSubmit = () => {
    if (totalCount === 0) {
      Toast.info('请先选择服饰或人员');
      return;
    }

    // 获取用户信息中的 id（人员id）
    const userInfo = Taro.getStorageSync(StorageKey.USER_INFO) as any;
    const personId = userInfo?.id;
    
    if (!personId) {
      Toast.info('请先登录');
      return;
    }

    // 构建请求参数
    const requestData = {
      id: personId, // 人员id
      bigFourDTOList: persons.map((person) => person.id), // 人员安排ID列表
      companyId: Taro.getStorageSync(StorageKey.SHOP_ID), // 商店ID
      orderDressDTOList: dresses.map((dress) => ({
        dressId: dress.id, // 服饰ID
        amount: dress.amount || 1, // 数量
        orderType: dress.orderType || 30, // 默认租赁
        remark: dress.remark || '', // 备注
      })),
    };

    submitPreselect(requestData);
  };

  return (
    <BasicLayout className="preselect-page" title='预选'>
      {totalCount === 0 ? (
        <View className="empty-container">
          <Empty description="暂无预选内容" />
        </View>
      ) : (
        <View className="page-content">
          {/* 人员安排 */}
          {persons.length > 0 && (
            <View className="section">
              <View className="section-title">人员安排</View>
              <View className="person-list">
                {persons.map((person) => (
                  <View key={person.id} className="person-item">
                    <View className="person-info">
                      <Text className="person-type">{getPersonTypeName(person.bigType)}</Text>
                      <Text className="person-name">{person.name || '未知'}</Text>
                      {person.price !== undefined && (
                        <Text className="person-price">¥{person.price}</Text>
                      )}
                    </View>
                    <View
                      className="person-remove"
                      onClick={() => {
                        removePerson(person.id);
                        Toast.info('已移除');
                      }}
                    >
                      <View className="remove-icon">×</View>
                    </View>
                  </View>
                ))}
              </View>
            </View>
          )}

          {/* 服装 */}
          {dresses.length > 0 && (
            <View className="section">
              <View className="section-title">服装</View>
              <View className="dress-list">
                {dresses.map((dress) => (
                  <DressItem 
                    key={dress.id} 
                    item={dress} 
                    onDelete={(id) => {
                      removeDress(Number(id));
                      Toast.info('已移除');
                    }}
                  />
                ))}
              </View>
            </View>
          )}

          {/* 总数 */}
          {totalCount > 0 && (
            <View className="total-section">
              <Text className="total-text">总数: {totalCount}</Text>
            </View>
          )}
        </View>
      )}

      {/* 提交按钮 */}
      <View className="submit-section">
        <Button
          type="default"
          className="record-button"
          onClick={() => {
            // 检查是否已登录
            const token = Taro.getStorageSync(StorageKey.TOKEN);
            if (!token) {
              // 未登录，弹窗提示
              Toast.confirm({
                title: '提示',
                content: '请先登录后再查看预选记录',
                confirmText: '去登录',
                cancelText: '取消',
                success: (res) => {
                  if (res.confirm) {
                    // 保存当前页面路径和参数，用于登录后返回
                    const currentPath = router.path;
                    const query = router.params;
                    const paramsString = qs.stringify(query);
                    const returnPath = `${currentPath}${paramsString ? `?${paramsString}` : ''}`;
                    Taro.setStorageSync(StorageKey.APP_START_REDIRECT_PATH, returnPath);
                    // 跳转到登录页面
                    Taro.navigateTo({ url: '/pages/user/login/index' });
                  }
                },
              });
              return;
            }
            RouterUtil.navigateTo('/pages/preselect/record/index');
          }}
        >
          预选记录
        </Button>
        <Button
          type="primary"
          className="submit-button"
          onClick={handleSubmit}
          disabled={totalCount === 0 || submitting}
          loading={submitting}
        >
          提交预选
        </Button>
      </View>
    </BasicLayout>
  );
};

export default Preselect;
